<template>
  <div class="dynamic-table-container">
    <CommonSearch
      ref="searchRef"
      v-model="queryForm"
      v-model:isLoading="tableData.isLoading"
      :search-data="searchData"
      @fetched-data="fetchedData"
    >
      <template #extendOtherOperate>
        <el-button
          :disabled="!selectionList.length && !subTableData.datalist.length"
          :icon="CircleCheckFilled"
          type="primary"
          @click="onHandleConfirmSelection"
        >
          确认选择
        </el-button>
      </template>
    </CommonSearch>
    <vxe-table
      align="center"
      :auto-resize="true"
      :border="true"
      :data="tableData.datalist"
      :max-height="tableData.maxHeight"
      :row-config="{ useKey: true }"
      :stripe="true"
      @checkbox-all="handleSelectionChange"
      @checkbox-change="handleSelectionChange"
      @radio-change="handleRadioChange"
      @sort-change="handleSorted"
    >
      <vxe-column v-if="isOnlyPrimaryTable" fixed="left" type="checkbox" width="60px" />
      <vxe-column v-else fixed="left" type="radio" width="60px" />
      <vxe-column fixed="left" title="序号" type="seq" width="60px" />
      <template v-for="item in tableData.columnList" :key="item.value">
        <vxe-column
          :field="item.value"
          :show-overflow="item.overflow"
          :sortable="!!item.sortable"
          :title="item.label"
          :width="item.width"
        >
          <template #default="{ row }">
            <template v-if="row && row.senum && row.senum[item.value]">
              <span :style="{ color: row.senum[item.value].color }">
                {{ row.senum[item.value].names }}
              </span>
            </template>
            <template v-else>{{ row[item.value] }}</template>
          </template>
        </vxe-column>
      </template>
    </vxe-table>
    <div class="pager">
      <vxe-pager
        v-model:current-page="queryForm.pageNum"
        v-model:page-size="queryForm.pageSize"
        :layouts="['Total', 'Number', 'Sizes', 'PrevJump', 'PrevPage', 'NextPage', 'NextJump', 'FullJump']"
        :total="tableData.total"
        @page-change="handlePageChange"
      />
    </div>
    <vxe-table
      v-if="!isOnlyPrimaryTable"
      align="center"
      :auto-resize="true"
      :border="true"
      class="sub-table-wrap"
      :data="subTableData.datalist"
      :max-height="subTableData.maxHeight"
      :row-config="{ useKey: true }"
      :stripe="true"
    >
      <vxe-column fixed="left" title="序号" type="seq" width="60px" />
      <template v-for="item in subTableData.columnList" :key="item.value">
        <vxe-column
          :field="item.value"
          :show-overflow="item.overflow"
          :sortable="!!item.sortable"
          :title="item.label"
          :width="item.width"
        >
          <template #default="{ row }">
            <template v-if="row && row.senum && row.senum[item.value]">
              <span :style="{ color: row.senum[item.value].color }">
                {{ row.senum[item.value].names }}
              </span>
            </template>
            <template v-else>{{ row[item.value] }}</template>
          </template>
        </vxe-column>
      </template>
    </vxe-table>
  </div>
</template>

<script>
import CommonSearch from "@/plugins/search/CommonSearch.vue";
import { CircleCheckFilled } from "@element-plus/icons-vue";
import { doSorted, getList } from "@/api/mains";

export default defineComponent({
  name: "DynamicTableDialog",
  components: { CommonSearch },
  props: {
    dynamicConfig: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  emits: {
    "on-handle-confirm-selection": null
  },

  setup(props, { emit }) {
    const { proxy } = getCurrentInstance();
    const queryForm = ref({ pageNum: 1, pageSize: 10, sorts: "" });
    const { columnList, url, querys } = props.dynamicConfig.dialogTableConfig?.primaryTable || {};

    const { columnList: subColumnList = [], url: subUrl, paramsFileds } = props.dynamicConfig.dialogTableConfig?.subTable || {};

    const selectionList = ref([]);
    const tableData = reactive({
      border: true,
      maxHeight: 300,
      datalist: [],
      isShowPagination: true,
      showSummary: false,
      total: 0,
      isSelectRow: true,
      isLoading: false,
      columnList: columnList || []
    });
    const subTableData = reactive({
      isLoading: false,
      maxHeight: 200,
      datalist: [],
      columnList: subColumnList || []
    });
    /**
     * common搜索传入参数
     */
    const searchData = reactive({
      //containerClass: 'up-down', // 布局搜索在上，功能操作在下

      queryUrl: url || "", //掉用url传入
      selectionIds: [], // table 选择中行数，批量删除要用到
      querys: querys || []
    });

    const fetchedData = res => {
      //数据加载完成赋予的操作,例如表格值赋予值
      tableData.datalist = res.data.rows;
      tableData.total = res.data.total;
    };

    const isOnlyPrimaryTable = computed(() => {
      return !url || !subColumnList.length;
    });

    const getSubList = async keyValue => {
      subTableData.isLoading = true;
      const key = paramsFileds?.key || "mainid";
      const { datas } = await getList(subUrl, {
        [key]: keyValue
      });
      subTableData.datalist = datas || [];
      subTableData.isLoading = false;
    };

    const handleRadioChange = val => {
      const { newValue } = val || {};
      searchData.selectionIds = [newValue];
      const valueKey = paramsFileds?.valueKey || "id";
      const keyValue = newValue?.[valueKey];
      if (keyValue) {
        getSubList(keyValue);
      }
    };

    /**
     * 处理table翻页以及换页面size
     * @param {} param0
     */
    const handlePageChange = ({ currentPage, pageSize }) => {
      queryForm.value.pageNum = currentPage;
      queryForm.value.pageSize = pageSize;
    };

    /**
     * 点击table排序
     * @param {} val
     */
    const handleSorted = async sortValue => {
      const { field, order } = sortValue.column;
      const val = {
        prop: field,
        order: order === "desc" ? "descending" : order
      };

      doSorted(val, queryForm.value);
    };

    const handleSelectionChange = val => {
      const { records = [] } = val || {};
      selectionList.value = records;
    };

    /**
     * 确认选择
     */
    const onHandleConfirmSelection = () => {
      const { selectionIds } = searchData;

      if (selectionIds.length || selectionList.value.length) {
        const emitData = isOnlyPrimaryTable.value ? selectionList.value : subTableData.datalist;
        emit("on-handle-confirm-selection", emitData);
      } else {
        proxy.$baseMessage("没有选中行", "error");
      }
    };
    return {
      queryForm,
      tableData,
      subTableData,
      searchData,
      isOnlyPrimaryTable,
      selectionList,
      fetchedData,
      getSubList,
      onHandleConfirmSelection,
      handleRadioChange,
      handlePageChange,
      handleSorted,
      handleSelectionChange,
      CommonSearch,
      CircleCheckFilled
    };
  }
});
</script>

<style lang="scss" scoped>
.dynamic-table-container {
  .sub-table-wrap {
    margin-top: 15px;
  }
}
</style>
